package com.googlecode.iiddefecttracker.service;

import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

/**
 * I am responsible for populating the configured datasource
 */
public class HsqldbSchemaAndDataPopulator implements InitializingBean {
    
    private JdbcTemplate template;
    
    /**
     * 
     */
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(template, "dataSource required");
        
        // add tables to represent bug tracking domain instances.
        template
                .execute("CREATE TABLE PROJECTS("
                        + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY,"
                        + "NAME VARCHAR_IGNORECASE(50) NOT NULL, "
                        + "VERSION VARCHAR_IGNORECASE(50) NOT NULL, "
                        + "DESCRIPTION VARCHAR_IGNORECASE(200) NOT NULL" + ");");
        
        template
                .execute("CREATE TABLE DEFECTS("
                        + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY,"
                        + "PROJECT_ID BIGINT NOT NULL, "
                        + "SUMMARY VARCHAR_IGNORECASE(200) NOT NULL, "
                        + "STEPSTORECREATE VARCHAR_IGNORECASE(1000) NOT NULL, "
                        + "RESULT VARCHAR_IGNORECASE(1000) NOT NULL, "
                        + "EXPECTEDRESULT VARCHAR_IGNORECASE(1000) NOT NULL, "
                        + "WORKAROUND VARCHAR_IGNORECASE(1000), "
                        + "CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PROJECT_ID)REFERENCES PROJECTS(ID)"
                        + ");");
        
        template
                .execute("INSERT INTO projects (name, version, description) VALUES ('Test Project', 'prototype', 'A description not longer than 200 chars of what project is.');");
        template
                .execute("INSERT INTO projects (name, version, description) VALUES ('Test Project 2', '0.1', 'Smaller description of project here.');");
        
        template
                .execute("INSERT INTO defects (project_id, summary, stepstorecreate, result, expectedresult, workaround) VALUES (1, 'Bug with x screen when saving y', 'recreate by: ', 'Result is unable to save x, get error message', 'should be able to save', null);");
        
    }
    
    public void setDataSource(final DataSource dataSource) {
        this.template = new JdbcTemplate(dataSource);
    }
    
}
